<template>
	<div></div>
</template>

<script>
	import 'viewerjs/dist/viewer.css';
	import { api as viewerApi } from 'v-viewer';
	export default {
		props: {
			url: {
				type: String,
				default: '',
			},
			ract: {
				type: Object,
				default: () => {},
			},
			on: {
				type: Object,
				default: () => {},
			},
		},
		data() {
			return {
				$viewer: null,
			};
		},
		mounted() {
			if (this.url) {
				this.$viewer = viewerApi({
					options: {
						toolbar: true,
						// initialViewIndex: 1,
						navbar: false,
						backdrop: false,
						title: false,
						button: false,
						container: this.$attrs.container,
						zIndex: 50000,
						viewed: () => {
							this.viewed();
							this.on?.img?.viewed?.();
							this.rendered();
						},
						shown: (a, b, c) => {
							// console.log(a, b, c);
							this.on?.img?.shown?.();
						},
						hidden: () => {
							this.$emit('unmount');
						},
						hide: () => {},
					},
					images: this.url.split(','),
				});
			}
		},
		beforeDestroy() {
			try {
				this.$viewer?.destroy();
			} catch (error) {
				console.error(error);
			}
		},
		methods: {
			resize({ x, y, width, height }) {
				this.toCenter();
			},
			toCenter() {
				let {
					imageData: { width, height, naturalHeight, naturalWidth },
					viewer,
				} = this.$viewer;
				const boxWidth = isNaN(
					parseFloat(getComputedStyle(viewer).width),
				)
					? 0
					: parseFloat(getComputedStyle(viewer).width);
				const boxHeigth = isNaN(
					parseFloat(getComputedStyle(viewer).height),
				)
					? 0
					: parseFloat(getComputedStyle(viewer).height);

				let adaptionWidthRatio = (boxWidth * 0.9) / naturalWidth;
				let adaptionHeightRatio = (boxHeigth * 0.9) / naturalHeight;
				let adaptionRatio = Math.min(
					adaptionWidthRatio,
					adaptionHeightRatio,
				);
				this.$viewer.reset();
				this.$viewer.zoomTo(adaptionRatio, false, {
					x: 0,
					y: 0,
				});
				let currentWidth = naturalWidth * adaptionRatio;
				let currentHeight = naturalHeight * adaptionRatio;

				this.$viewer.moveTo(
					(boxWidth - currentWidth) / 2,
					(boxHeigth - currentHeight) / 2,
				);
			},
			viewed() {
				let viewerReset = document.querySelector('.viewer-reset');
				viewerReset.onclick = e => {
					e.stopPropagation();
					this.toCenter();
				};

				this.toCenter();
			},
			rendered() {
				this.$emit('rendered');
			},
			error() {
				this.$emit('error');
			},
		},
	};
</script>

<style>
	::v-deep .viewer-button.viewer-close {
		display: none !important;
	}
</style>
